package xiegd.com.springbootuse.demo.delay;

/**
 * @Author: xieguangda
 * @Description:
 * @Date: 2023/9/8 16:12
 */

import redis.clients.jedis.Jedis;

import java.util.Set;

public class RedisDelayQueueDemo {
    private static final String QUEUE_NAME = "delay-queue";

    public static void main(String[] args) throws InterruptedException {
        Jedis jedis = new Jedis("www.hinzzz.cn", 6379);
        // 向队列中添加元素
        jedis.zadd(QUEUE_NAME, System.currentTimeMillis() + 4000, "message 1");
        jedis.zadd(QUEUE_NAME, System.currentTimeMillis() + 2000, "message 2");
        jedis.zadd(QUEUE_NAME, System.currentTimeMillis() + 6000, "message 3");
        while (true) {
            Set<String> messages = jedis.zrangeByScore(QUEUE_NAME, 0, System.currentTimeMillis(), 0, 1);
            if (!messages.isEmpty()) {
                String message = messages.iterator().next();
                jedis.zrem(QUEUE_NAME, message);
                System.out.println(message);
            } else {
                Thread.sleep(1000);
            }
        }
    }
}

